Coverage Report

Created: 2026-11-19 22:35

next uncovered line (L), next uncovered region (R), next uncovered branch (B)
D:\a\cssh-rs\cssh-rs\cssh-rs-core\src\client\mod.rs
Line
Count
Source
1
//! Client implementation
2
3
#![deny(clippy::implicit_return)]
4
#![allow(clippy::needless_return, clippy::doc_overindented_list_items)]
5
#![warn(missing_docs)]
6
7
mod console_mode;
8
mod dispatch;
9
pub(crate) mod input_bytes;
10
mod pty;
11
12
use std::ffi::OsStr;
13
use std::fs::File;
14
use std::io::{BufReader, Read, Write};
15
use std::path::Path;
16
use std::sync::Arc;
17
use std::time::Duration;
18
19
use log::{error, info, warn};
20
use portable_pty::MasterPty;
21
use ssh2_config::{ParseRule, SshConfig};
22
use tokio::sync::{oneshot, watch};
23
use windows::Win32::System::Console::{
24
    CONSOLE_CHARACTER_ATTRIBUTES, KEY_EVENT, WINDOW_BUFFER_SIZE_EVENT,
25
};
26
27
use cssh_rs_meta::PACKAGE_NAME;
28
use cssh_rs_platform::ControlChannelClient;
29
use cssh_rs_protocol::v1::capability::negotiate_max_frame_len;
30
use cssh_rs_protocol::v1::codec::{decode_frames, encode_frame};
31
use cssh_rs_protocol::v1::handshake::{Hello, Welcome};
32
use cssh_rs_protocol::v1::limits::DEFAULT_MAX_FRAME_LEN;
33
use cssh_rs_protocol::v1::message::DaemonToClient;
34
use cssh_rs_protocol::v1::version::{ProtocolVersion, Role};
35
use cssh_rs_protocol::ClientState;
36
37
use crate::client::console_mode::ConsoleModeGuard;
38
use crate::client::dispatch::dispatch_daemon_message;
39
use crate::client::input_bytes::key_event_record_to_bytes;
40
use crate::client::pty::{
41
    console_viewport_size, scan_and_answer_dsr, spawn_client_pty, write_to_master, SharedWriter,
42
};
43
use crate::utils::config::ClientConfig;
44
use crate::utils::windows::{
45
    get_console_title, read_console_input, set_console_palette, snapshot_console_palette,
46
    tinted_palette, ConsolePaletteSnapshot, WindowsApi, WindowsControlChannelClient,
47
};
48
49
/// Length in bytes of the big-endian `u32` frame length prefix.
50
const LENGTH_PREFIX_LEN: usize = 4;
51
52
/// Duration of the action-feedback flash painted on a highlighted client
53
/// when the user toggles the state.
54
const HIGHLIGHT_FLASH_DURATION: Duration = Duration::from_millis(250);
55
56
/// A state repaint: `Tint` swaps the console palette so the window background
57
/// takes on the state color, `Restore` writes the saved palette back.
58
#[derive(Clone, Copy, PartialEq, Eq, Debug)]
59
enum ConsolePaint {
60
    Restore,
61
    Tint(CONSOLE_CHARACTER_ATTRIBUTES),
62
}
63
64
/// Resolve the steady-state paint intent for `(state, highlighted)`; the
65
/// highlight overlays the disabled color.
66
9
fn get_effective_color(
67
9
    state: ClientState,
68
9
    highlighted: bool,
69
9
    disabled_console_color: CONSOLE_CHARACTER_ATTRIBUTES,
70
9
    highlighted_console_color: CONSOLE_CHARACTER_ATTRIBUTES,
71
9
) -> ConsolePaint {
72
9
    if highlighted {
73
4
        return ConsolePaint::Tint(highlighted_console_color);
74
5
    }
75
5
    match state {
76
3
        ClientState::Active => return ConsolePaint::Restore,
77
2
        ClientState::Disabled => return ConsolePaint::Tint(disabled_console_color),
78
    }
79
9
}
80
81
/// Resolve the flash paint intent for `state`, bypassing the highlight overlay.
82
3
fn get_flash_color(
83
3
    state: ClientState,
84
3
    disabled_console_color: CONSOLE_CHARACTER_ATTRIBUTES,
85
3
) -> ConsolePaint {
86
3
    match state {
87
2
        ClientState::Active => return ConsolePaint::Restore,
88
1
        ClientState::Disabled => return ConsolePaint::Tint(disabled_console_color),
89
    }
90
3
}
91
92
/// Bundle of the state colors [`run_visuals_loop`] chooses between when
93
/// repainting the per-client console.
94
struct ConsolePalette {
95
    /// Pristine palette captured at startup; `None` (the palette could not be
96
    /// read) degrades every paint to a no-op.
97
    base: Option<ConsolePaletteSnapshot>,
98
    /// Color applied while [`ClientState::Disabled`].
99
    disabled: CONSOLE_CHARACTER_ATTRIBUTES,
100
    /// Color applied while the client is the highlighted submenu target.
101
    highlighted: CONSOLE_CHARACTER_ATTRIBUTES,
102
}
103
104
/// Repaint the console to the steady-state look for `(state, highlighted)`.
105
5
fn paint_steady(
106
5
    api: &dyn WindowsApi,
107
5
    state: ClientState,
108
5
    highlighted: bool,
109
5
    palette: &ConsolePalette,
110
5
    last: &mut Option<ConsolePaint>,
111
5
) {
112
5
    paint_console_color(
113
5
        api,
114
5
        get_effective_color(state, highlighted, palette.disabled, palette.highlighted),
115
5
        palette.base.as_ref(),
116
5
        last,
117
    );
118
5
}
119
120
/// Paint the action-feedback flash and return the deadline to clear it at.
121
1
fn start_flash(
122
1
    api: &dyn WindowsApi,
123
1
    state: ClientState,
124
1
    palette: &ConsolePalette,
125
1
    last: &mut Option<ConsolePaint>,
126
1
) -> tokio::time::Instant {
127
1
    paint_console_color(
128
1
        api,
129
1
        get_flash_color(state, palette.disabled),
130
1
        palette.base.as_ref(),
131
1
        last,
132
    );
133
1
    return tokio::time::Instant::now() + HIGHLIGHT_FLASH_DURATION;
134
1
}
135
136
/// Apply `target` if it differs from `last`, then update `last`.
137
///
138
/// `Tint` recolors the window by swapping the console palette; `Restore` writes
139
/// the pristine `base` palette back. Neither touches the screen-buffer cells, so
140
/// VT/24-bit text the palette cannot hold survives.
141
13
fn paint_console_color(
142
13
    api: &dyn WindowsApi,
143
13
    target: ConsolePaint,
144
13
    base: Option<&ConsolePaletteSnapshot>,
145
13
    last: &mut Option<ConsolePaint>,
146
13
) {
147
    // An unchanged repaint still costs a conhost LPC roundtrip and a WM_PAINT.
148
13
    if *last == Some(target) {
149
3
        return;
150
10
    }
151
    // No captured palette (unreadable at startup) degrades every paint to a no-op.
152
10
    let Some(
base9
) = base else {
153
1
        return;
154
    };
155
9
    let palette = match target {
156
5
        ConsolePaint::Tint(color) => tinted_palette(base, color),
157
4
        ConsolePaint::Restore => base.color_table,
158
    };
159
    // Leave `last` untouched on a failed write so the next transition retries
160
    // instead of recording a paint that never reached the screen.
161
9
    if !set_console_palette(api, &palette) {
162
1
        return;
163
8
    }
164
8
    *last = Some(target);
165
13
}
166
167
/// Resolve the username from the provided value or SSH config.
168
///
169
/// # Arguments
170
///
171
/// * `username` - Optional username to use. If None, will try to resolve from SSH config.
172
/// * `host` - The hostname (without port) to connect to.
173
/// * `config` - The client configuration containing SSH config path.
174
///
175
/// # Returns
176
///
177
/// The resolved username.
178
12
fn resolve_username(username: Option<String>, host: &str, config: &ClientConfig) -> String {
179
12
    if let Some(
val8
) = username {
180
8
        return val;
181
4
    }
182
183
4
    let mut ssh_config = SshConfig::default();
184
4
    let ssh_config_path = Path::new(config.ssh_config_path.as_str());
185
4
    if ssh_config_path.exists() {
186
2
        let mut reader = BufReader::new(
187
2
            File::open(ssh_config_path).expect("Could not open SSH configuration file."),
188
2
        );
189
2
        ssh_config = SshConfig::default()
190
2
            .parse(&mut reader, ParseRule::ALLOW_UNKNOWN_FIELDS)
191
2
            .expect("Failed to parse SSH configuration file");
192
2
    }
193
4
    return ssh_config.query(host).user.unwrap_or_default();
194
12
}
195
196
/// Build the SSH arguments from the username, host, port, and config.
197
///
198
/// # Arguments
199
///
200
/// * `username`    - The username to connect with.
201
/// * `host`        - The hostname to connect to.
202
/// * `port`        - Optional port number (0-65535).
203
/// * `config`      - The client config indicating how to call the SSH program.
204
///
205
/// # Returns
206
///
207
/// A vector of arguments ready to be passed to the SSH command.
208
12
fn build_ssh_arguments(
209
12
    username: &str,
210
12
    host: &str,
211
12
    port: Option<u16>,
212
12
    config: &ClientConfig,
213
12
) -> Vec<String> {
214
12
    let username_host = format!("{username}@{host}");
215
216
12
    let mut arguments = replace_argument_placeholders(
217
12
        &config.arguments,
218
12
        &config.username_host_placeholder,
219
12
        &username_host,
220
    );
221
222
    // Add port arguments if port was specified
223
12
    if let Some(
port9
) = port {
224
9
        arguments.push("-p".to_string());
225
9
        arguments.push(port.to_string());
226
9
    
}3
227
228
12
    return arguments;
229
12
}
230
231
/// Connect to the daemon control channel, retrying while the daemon binds it.
232
///
233
/// # Arguments
234
///
235
/// * `client`   - The control-channel client to connect.
236
/// * `endpoint` - Named-pipe path of the daemon control channel.
237
///
238
/// # Returns
239
///
240
/// `true` once connected, `false` after about 30 seconds of failed attempts.
241
#[cfg_attr(coverage_nightly, coverage(off))]
242
async fn connect_with_retry(client: &mut WindowsControlChannelClient, endpoint: &OsStr) -> bool {
243
    for _ in 0..600 {
244
        if client.connect(endpoint).await.is_ok() {
245
            return true;
246
        }
247
        tokio::time::sleep(Duration::from_millis(50)).await;
248
    }
249
    return false;
250
}
251
252
/// Exchange `Hello`s and receive the `Welcome`.
253
///
254
/// # Arguments
255
///
256
/// * `client` - The connected control-channel client.
257
///
258
/// # Returns
259
///
260
/// The negotiated maximum frame length and the bytes received past the
261
/// `Welcome`.
262
#[cfg_attr(coverage_nightly, coverage(off))]
263
pub(crate) async fn client_handshake(client: &mut WindowsControlChannelClient) -> (u32, Vec<u8>) {
264
    let hello = Hello {
265
        protocol_version: ProtocolVersion::new(1, 0),
266
        role: Role::Client,
267
        pid: std::process::id(),
268
        capabilities: Vec::new(),
269
        max_frame_len: DEFAULT_MAX_FRAME_LEN,
270
    };
271
    if let Ok(frame) = encode_frame(&hello, DEFAULT_MAX_FRAME_LEN) {
272
        if let Err(err) = client.send(&frame).await {
273
            warn!("Failed to send client Hello: {}", err);
274
        }
275
    }
276
277
    let mut pending = Vec::new();
278
    let max_frame_len =
279
        match read_message::<Hello>(client, &mut pending, DEFAULT_MAX_FRAME_LEN).await {
280
            Some(daemon_hello) => {
281
                negotiate_max_frame_len(DEFAULT_MAX_FRAME_LEN, daemon_hello.max_frame_len)
282
            }
283
            None => DEFAULT_MAX_FRAME_LEN,
284
        };
285
    let _ = read_message::<Welcome>(client, &mut pending, max_frame_len).await;
286
    return (max_frame_len, pending);
287
}
288
289
/// Receive until `pending` holds a complete frame, then split it off.
290
///
291
/// # Arguments
292
///
293
/// * `client`        - The connected control-channel client.
294
/// * `pending`       - Bytes received but not yet returned as a frame.
295
/// * `max_frame_len` - Largest frame body to accept.
296
///
297
/// # Returns
298
///
299
/// The frame including its length prefix, or `None` on disconnect, error, or
300
/// an oversized frame.
301
#[cfg_attr(coverage_nightly, coverage(off))]
302
async fn read_frame(
303
    client: &mut WindowsControlChannelClient,
304
    pending: &mut Vec<u8>,
305
    max_frame_len: u32,
306
) -> Option<Vec<u8>> {
307
    let mut buffer = [0u8; 8192];
308
    loop {
309
        if let Some(prefix) = pending.first_chunk::<LENGTH_PREFIX_LEN>() {
310
            let body_length = u32::from_be_bytes(*prefix);
311
            if body_length > max_frame_len {
312
                error!("Control frame length {} exceeds the maximum", body_length);
313
                return None;
314
            }
315
            let frame_length = LENGTH_PREFIX_LEN + body_length as usize;
316
            if pending.len() >= frame_length {
317
                return Some(pending.drain(..frame_length).collect());
318
            }
319
        }
320
        match client.recv(&mut buffer).await {
321
            Ok(0) => return None,
322
            Ok(received) => pending.extend_from_slice(&buffer[..received]),
323
            Err(err) => {
324
                error!("Control channel receive error: {}", err);
325
                return None;
326
            }
327
        }
328
    }
329
}
330
331
/// Read one frame and decode it as `T`.
332
#[cfg_attr(coverage_nightly, coverage(off))]
333
pub(crate) async fn read_message<T: serde::de::DeserializeOwned>(
334
    client: &mut WindowsControlChannelClient,
335
    pending: &mut Vec<u8>,
336
    max_frame_len: u32,
337
) -> Option<T> {
338
    let frame = read_frame(client, pending, max_frame_len).await?;
339
    let decoded = decode_frames::<T>(frame, max_frame_len).ok()?;
340
    return decoded.messages.into_iter().next();
341
}
342
343
/// Dispatch daemon messages until the daemon terminates or disconnects, or the
344
/// SSH child exits.
345
///
346
/// # Arguments
347
///
348
/// * `api`              - The Windows API implementation to use.
349
/// * `client`           - The connected control-channel client.
350
/// * `master`           - Shared PTY master writer.
351
/// * `child_pid`        - Process id of the SSH child.
352
/// * `state_sender`     - Watch sender for the client state.
353
/// * `highlight_sender` - Watch sender for the highlight flag.
354
/// * `max_frame_len`    - The negotiated maximum frame length.
355
/// * `pending`          - Bytes received during the handshake but not consumed.
356
/// * `child_exit`       - Receives the SSH child's exit code.
357
#[allow(clippy::too_many_arguments)]
358
#[cfg_attr(coverage_nightly, coverage(off))]
359
async fn run_control_channel(
360
    api: &dyn WindowsApi,
361
    mut client: WindowsControlChannelClient,
362
    master: SharedWriter,
363
    child_pid: u32,
364
    state_sender: &watch::Sender<ClientState>,
365
    highlight_sender: &watch::Sender<bool>,
366
    max_frame_len: u32,
367
    mut pending: Vec<u8>,
368
    mut child_exit: oneshot::Receiver<i32>,
369
) {
370
    loop {
371
        tokio::select! {
372
            frame = read_frame(&mut client, &mut pending, max_frame_len) => {
373
                let Some(frame) = frame else {
374
                    return;
375
                };
376
                let Ok(decoded) = decode_frames::<DaemonToClient>(frame, max_frame_len) else {
377
                    return;
378
                };
379
                for message in decoded.messages {
380
                    let flow = dispatch_daemon_message(
381
                        api,
382
                        message,
383
                        &*master,
384
                        child_pid,
385
                        state_sender,
386
                        highlight_sender,
387
                    );
388
                    if flow.is_break() {
389
                        return;
390
                    }
391
                }
392
            }
393
            exit_code = &mut child_exit => {
394
                if let Ok(code) = exit_code {
395
                    info!("SSH child exited with code {}", code);
396
                }
397
                return;
398
            }
399
        }
400
    }
401
}
402
403
/// Render the PTY output to this window from a dedicated thread.
404
///
405
/// # Arguments
406
///
407
/// * `reader` - Reader over the PTY master.
408
/// * `master` - Shared PTY master writer, for the DSR reply.
409
#[cfg_attr(coverage_nightly, coverage(off))]
410
fn spawn_output_reader(mut reader: Box<dyn Read + Send>, master: SharedWriter) {
411
    std::thread::spawn(move || {
412
        let mut carry = Vec::new();
413
        let mut buffer = [0u8; 8192];
414
        let mut stdout = std::io::stdout();
415
        while let Ok(received @ 1..) = reader.read(&mut buffer) {
416
            let rendered = scan_and_answer_dsr(&buffer[..received], &mut carry, &*master);
417
            let _ = stdout.write_all(&rendered);
418
            let _ = stdout.flush();
419
        }
420
    });
421
}
422
423
/// Forward this window's own keystrokes to the PTY master from a dedicated
424
/// thread, so a broadcast line stays editable here, and resize the PTY with
425
/// the console window.
426
///
427
/// # Arguments
428
///
429
/// * `api`    - The Windows API implementation to use.
430
/// * `writer` - Shared PTY master writer.
431
/// * `master` - PTY master to resize.
432
#[cfg_attr(coverage_nightly, coverage(off))]
433
fn spawn_local_input<A: WindowsApi + Clone + 'static>(
434
    api: A,
435
    writer: SharedWriter,
436
    master: Box<dyn MasterPty + Send>,
437
) {
438
    std::thread::spawn(move || loop {
439
        let record = read_console_input(&api);
440
        match u32::from(record.EventType) {
441
            KEY_EVENT => {
442
                let key = unsafe { record.Event.KeyEvent };
443
                if key.bKeyDown.as_bool() {
444
                    write_to_master(&*writer, &key_event_record_to_bytes(&key));
445
                }
446
            }
447
            // The event reports the buffer size; the PTY follows the visible window.
448
            WINDOW_BUFFER_SIZE_EVENT => {
449
                if let Some(size) = console_viewport_size(&api) {
450
                    if let Err(err) = master.resize(size) {
451
                        warn!("Failed to resize the PTY: {}", err);
452
                    }
453
                }
454
            }
455
            _ => {}
456
        }
457
    });
458
}
459
460
/// Replaces placeholders in SSH command arguments.
461
///
462
/// # Arguments
463
///
464
/// * `arguments` - The argument templates.
465
/// * `placeholder` - The placeholder string to replace.
466
/// * `replacement` - The value to replace the placeholder with.
467
///
468
/// # Returns
469
///
470
/// A vector of arguments with placeholders replaced.
471
12
fn replace_argument_placeholders(
472
12
    arguments: &[String],
473
12
    placeholder: &str,
474
12
    replacement: &str,
475
12
) -> Vec<String> {
476
12
    return arguments
477
12
        .iter()
478
30
        .
map12
(|arg| return arg.replace(placeholder, replacement))
479
12
        .collect();
480
12
}
481
482
/// Splits `host` on its trailing `:port` suffix (if any) and parses
483
/// the port. An invalid `:port` is logged and treated as absent so
484
/// the CLI port can still apply.
485
///
486
/// # Arguments
487
///
488
/// * `host` - Raw host argument, optionally with `:port` suffix.
489
///
490
/// # Returns
491
///
492
/// `(host_without_port, inline_port)`.
493
0
fn split_host_and_inline_port(host: &str) -> (&str, Option<u16>) {
494
0
    let (bare_host, port_str) = host
495
0
        .rsplit_once(':')
496
0
        .map_or((host, None), |(h, p)| return (h, Some(p)));
497
0
    let inline_port = port_str.and_then(|p| {
498
0
        return p
499
0
            .parse::<u16>()
500
0
            .map_err(|e| {
501
0
                warn!("Invalid port '{}': {}. Using default SSH port.", p, e);
502
0
            })
503
0
            .ok();
504
0
    });
505
0
    return (bare_host, inline_port);
506
0
}
507
508
/// Builds the console window title shown to the user.
509
///
510
/// # Arguments
511
///
512
/// * `resolved_username` - Username after SSH config resolution.
513
/// * `host`              - Bare hostname.
514
/// * `port`              - Effective port (inline or CLI), if any.
515
///
516
/// # Returns
517
///
518
/// The console title string in `cssh-rs - user@host[:port]` form.
519
0
fn build_console_title(resolved_username: &str, host: &str, port: Option<u16>) -> String {
520
0
    let title_host = if let Some(port) = port {
521
0
        format!("{host}:{port}")
522
    } else {
523
0
        host.to_string()
524
    };
525
0
    return format!("{PACKAGE_NAME} - {resolved_username}@{title_host}");
526
0
}
527
528
/// Keeps the console window title pinned to `console_title`, since
529
/// the SSH child can overwrite it on connect.
530
///
531
/// # Arguments
532
///
533
/// * `api`           - The Windows API implementation to use.
534
/// * `console_title` - The title to (re)apply.
535
0
async fn run_title_loop(api: &dyn WindowsApi, console_title: String) {
536
    loop {
537
0
        if console_title != get_console_title(api) {
538
0
            api.set_console_title(console_title.as_str())
539
0
                .unwrap_or_else(|err| {
540
0
                    error!("Failed to set console title: {}", err);
541
0
                });
542
0
        }
543
0
        tokio::time::sleep(Duration::from_millis(5)).await;
544
    }
545
}
546
547
/// Drive the per-client console color: track `state_receiver` and
548
/// `highlight_receiver`, paint the steady-state combination, and flash the
549
/// underlying state color for [`HIGHLIGHT_FLASH_DURATION`]. A `None` `base`
550
/// (the palette could not be read) degrades all painting to a no-op.
551
2
async fn run_visuals_loop(
552
2
    api: &dyn WindowsApi,
553
2
    mut state_receiver: watch::Receiver<ClientState>,
554
2
    mut highlight_receiver: watch::Receiver<bool>,
555
2
    base: Option<ConsolePaletteSnapshot>,
556
2
    disabled_console_color: CONSOLE_CHARACTER_ATTRIBUTES,
557
2
    highlighted_console_color: CONSOLE_CHARACTER_ATTRIBUTES,
558
2
) {
559
2
    let palette = ConsolePalette {
560
2
        base,
561
2
        disabled: disabled_console_color,
562
2
        highlighted: highlighted_console_color,
563
2
    };
564
2
    let mut prev_state = *state_receiver.borrow_and_update();
565
2
    let mut prev_highlight = *highlight_receiver.borrow_and_update();
566
    // The console shows its pristine palette at startup, so the initial paint is
567
    // a no-op restore rather than an unknown state.
568
2
    let mut last_painted: Option<ConsolePaint> = Some(ConsolePaint::Restore);
569
2
    let mut flash_until: Option<tokio::time::Instant> = None;
570
571
2
    paint_steady(api, prev_state, prev_highlight, &palette, &mut last_painted);
572
573
    loop {
574
        // Independent watch channels: `state_receiver` and `highlight_receiver` may be observed out of send-order, so the flash branch can fire (or not) on stale `prev_highlight`.
575
6
        tokio::select! {
576
6
            
state_changed5
= state_receiver.changed() => {
577
5
                if state_changed.is_err() {
578
2
                    return;
579
3
                }
580
3
                prev_state = *state_receiver.borrow_and_update();
581
3
                if prev_highlight {
582
1
                    flash_until =
583
1
                        Some(start_flash(api, prev_state, &palette, &mut last_painted));
584
2
                } else {
585
2
                    paint_steady(api, prev_state, prev_highlight, &palette, &mut last_painted);
586
2
                    flash_until = None;
587
2
                }
588
            }
589
6
            
highlight_changed0
= highlight_receiver.changed() => {
590
0
                if highlight_changed.is_err() {
591
0
                    return;
592
0
                }
593
0
                let next_highlight = *highlight_receiver.borrow_and_update();
594
0
                if next_highlight == prev_highlight {
595
0
                    continue;
596
0
                }
597
0
                prev_highlight = next_highlight;
598
0
                flash_until = None;
599
0
                paint_steady(api, prev_state, prev_highlight, &palette, &mut last_painted);
600
            }
601
6
            _ = async {
602
6
                match flash_until {
603
1
                    Some(deadline) => tokio::time::sleep_until(deadline).await,
604
5
                    None => std::future::pending::<()>().await,
605
                }
606
1
            } => {
607
1
                flash_until = None;
608
1
                paint_steady(api, prev_state, prev_highlight, &palette, &mut last_painted);
609
1
            }
610
        }
611
    }
612
2
}
613
614
/// The entrypoint for the `client` subcommand with API dependency injection.
615
///
616
/// Runs `ssh` inside a ConPTY that receives both the daemon-broadcast and this
617
/// window's own keystrokes, and renders its output to this window.
618
///
619
/// # Arguments
620
///
621
/// * `api`            - The Windows API implementation to use.
622
/// * `host`           - The name of the host to connect to, optionally with `:port` suffix.
623
/// * `username`       - The username to be used. Resolved from the SSH config if `None`.
624
/// * `cli_port`       - Optional port from CLI option. Inline port takes precedence.
625
/// * `daemon_channel` - Named-pipe path of the daemon control channel.
626
/// * `config`         - A reference to the `ClientConfig`.
627
#[cfg_attr(coverage_nightly, coverage(off))]
628
pub async fn main<A: WindowsApi + Clone + 'static>(
629
    api: &A,
630
    host: String,
631
    username: Option<String>,
632
    cli_port: Option<u16>,
633
    daemon_channel: Option<String>,
634
    config: &ClientConfig,
635
) {
636
    // Shield this client from relayed CTRL+C/CTRL+Break so only the SSH child reacts.
637
    if let Err(err) = api.install_console_ctrl_handler() {
638
        warn!("Failed to install console control handler: {}", err);
639
    }
640
641
    let Some(daemon_channel) = daemon_channel else {
642
        error!("The client requires --daemon-channel");
643
        return;
644
    };
645
646
    // Snapshot the palette before the SSH child writes, so a later tint restores
647
    // the pristine colors and reads the true default attribute rather than one
648
    // the child may have changed.
649
    let base_palette = snapshot_console_palette(api);
650
    let _console_mode_guard = ConsoleModeGuard::apply(api);
651
652
    let (state_sender, state_receiver) = watch::channel(ClientState::Active);
653
    let (highlight_sender, highlight_receiver) = watch::channel(false);
654
655
    let (host, inline_port) = split_host_and_inline_port(&host);
656
    let port = inline_port.or(cli_port);
657
    let resolved_username = resolve_username(username, host, config);
658
    let console_title = build_console_title(&resolved_username, host, port);
659
660
    let mut control_channel = WindowsControlChannelClient::new();
661
    if !connect_with_retry(&mut control_channel, OsStr::new(&daemon_channel)).await {
662
        error!("Failed to connect to the daemon control channel");
663
        return;
664
    }
665
    let (max_frame_len, pending) = client_handshake(&mut control_channel).await;
666
667
    let ssh_arguments = build_ssh_arguments(&resolved_username, host, port, config);
668
    let pty_size = console_viewport_size(api).unwrap_or_default();
669
    let mut pty = match spawn_client_pty(&config.program, &ssh_arguments, pty_size) {
670
        Ok(pty) => pty,
671
        Err(err) => {
672
            error!("Failed to spawn `{}` under a PTY: {}", config.program, err);
673
            return;
674
        }
675
    };
676
677
    spawn_output_reader(pty.reader, Arc::clone(&pty.writer));
678
    spawn_local_input(api.clone(), Arc::clone(&pty.writer), pty.master);
679
680
    let mut child_killer = pty.child.clone_killer();
681
    let (child_exit_sender, child_exit_receiver) = oneshot::channel();
682
    tokio::task::spawn_blocking(move || {
683
        let exit_code = pty
684
            .child
685
            .wait()
686
            .map_or(1, |status| return status.exit_code() as i32);
687
        let _ = child_exit_sender.send(exit_code);
688
    });
689
690
    let control_task = run_control_channel(
691
        api,
692
        control_channel,
693
        pty.writer,
694
        pty.child_pid,
695
        &state_sender,
696
        &highlight_sender,
697
        max_frame_len,
698
        pending,
699
        child_exit_receiver,
700
    );
701
    let title_task = run_title_loop(api, console_title);
702
    let visuals_task = run_visuals_loop(
703
        api,
704
        state_receiver,
705
        highlight_receiver,
706
        base_palette,
707
        CONSOLE_CHARACTER_ATTRIBUTES(config.disabled_console_color),
708
        CONSOLE_CHARACTER_ATTRIBUTES(config.highlighted_console_color),
709
    );
710
711
    // The title and visuals tasks are infinite by construction; if either
712
    // ever completes, that is a logic bug, not a shutdown path.
713
    tokio::select! {
714
        _ = control_task => {}
715
        _ = title_task => {
716
            panic!("Title task should never complete");
717
        }
718
        _ = visuals_task => {
719
            panic!("Visuals task should never complete");
720
        }
721
    }
722
723
    if let Err(err) = child_killer.kill() {
724
        warn!("Failed to kill SSH child on shutdown: {}", err);
725
    }
726
}
727
728
#[cfg(test)]
729
#[path = "../tests/client/test_mod.rs"]
730
mod test_mod;